package com.java.androidmarket.aspect;

import com.java.androidmarket.exception.ApiException;
import com.java.androidmarket.utils.JWTUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * description:
 * author:张腾
 * date:2021-05-28
 */

@Aspect
@Component
public class CheckUserAspect {

    @Pointcut("@annotation(checkUser)")
    public void pointCut(CheckUser checkUser){
    }

    @Around("pointCut(checkUser)")
    public Object arround(ProceedingJoinPoint pjp,CheckUser checkUser) throws Throwable{

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Token");

        Object[] args = pjp.getArgs();
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        String[] parameterNames = methodSignature.getParameterNames();
        String userId ="";
        for (int i = 0; i < parameterNames.length; i++) {
            if (parameterNames[i].equals("userId")){
                userId = String.valueOf(args[i]);
                break;
            }
        }
        if (!JWTUtils.DecodedGetID(token).equals(userId)) {
            throw new ApiException("-1","非法进入");
        }
        return pjp.proceed();
    }
}
